//
// Created by fairy on 2025/7/1.
//
#pragma once
#include "m25pxx.hpp"

#include <circuit_tester.hpp>
#include <core_common.hpp>
#include <cstring>
#include <delay.hpp>
#include <hal.hpp>
#include <registers.hpp>
#include <usart.hpp>

namespace core
{
    class control
    {
        static inline uint8_t adc_index = 0;
        volatile static inline uint16_t adc_value = 0;

    public:
        ALWAYS_INLINE static void init();
        inline static void handler();
        ALWAYS_INLINE static auto set_adc_value(auto value) { adc_value = value; }
    };
}// namespace core


static volatile int sample_index = 0;
// 初始化函数
void core::control::init()
{
    CircuitTester::init();

}

void core::control::handler()
{

    using CCT = gui::interface::CCT;

    if (CCT::get_generate_state()) {
        // 获取参数
        CircuitTester::measure_base_param();
    }
    // else {
    //     gui::interface::CCT::clear_text();
    //     delay::ms(50);
    // }

    if (CCT::get_generate_chart_state()) {
        // 扫频
        CircuitTester::sweep_freq();

    }
    // else if (CCT::get_had_generate_chart_state()) {
    //     // // 获取数组引用
    //     CircuitTester::get_amplify_freq().fill(0);
    //     CCT::generate_data(CircuitTester::get_amplify_freq());
    // }

    if (CCT::get_generate_bug_state()) {
        CircuitTester::judge_bug_type();
    }
    else if (CCT::get_generate_bug_state()) { CCT::clear_bug_text(); }

    // 按下存储数据 不能让它一直执行，按一下执行一次 未测试谨慎使用
    if (CCT::get_generate_store_state()) {
        using m25p16 = bsp::m25p16::control;
        // id=m25p16::read_id();
        m25p16::chip_erase();
        CircuitTester::get_flash_write_data().fill(5);
        CircuitTester::get_flash_read_data().fill(1);
        // 上面这段又可以替换下面这段
        // std::ranges::fill(CircuitTester::get_flash_write_data(), 5);
        // std::ranges::fill(CircuitTester::get_flash_read_data(), 1);
        //上面这段等效替代memset，但不用给大小
        // memset(flash_write_data, 1, sizeof(flash_write_data));
        // memset(flash_read_data, 1, sizeof(flash_read_data));
        while (m25p16::async_is_busy()) { hal::delay::ms(1); }
        m25p16::buffer_read(CircuitTester::get_flash_read_data().data(), 0, 100);
        hal::delay::ms(100);
        m25p16::page_write<true>(CircuitTester::get_flash_write_data().data(), 0, 50);
        hal::delay::ms(100);
        m25p16::buffer_read(CircuitTester::get_flash_read_data().data(), 0, 50);
        hal::delay::ms(100);
    }

    if (CCT::get_generate_bluetooth_state()) {
        // 蓝牙
    }
}